package com.jee.support.memcached;

import java.io.IOException;

import net.rubyeye.xmemcached.MemcachedClient;
import net.rubyeye.xmemcached.MemcachedClientBuilder;
import net.rubyeye.xmemcached.XMemcachedClient;
import net.rubyeye.xmemcached.XMemcachedClientBuilder;
import net.rubyeye.xmemcached.command.BinaryCommandFactory;
import net.rubyeye.xmemcached.utils.AddrUtil;

public class Cache {
    private static MemcachedClient memcachedClient;

    public static void init(String address) throws IOException {
        MemcachedClientBuilder builder = new XMemcachedClientBuilder(
                AddrUtil.getAddresses(address));
          builder.setCommandFactory(new BinaryCommandFactory());//use binary protocol
        memcachedClient = builder.build();
//        try {
//            memcachedClient.set("hello", 0, "Hello,xmemcached");
//            String value = memcachedClient.get("hello");
//            System.out.println("hello=" + value);
//            memcachedClient.delete("hello");
//            value = memcachedClient.get("hello");
//            System.out.println("hello=" + value);
//        } catch (MemcachedException e) {
//            System.err.println("MemcachedClient operation fail");
//            e.printStackTrace();
//        } catch (TimeoutException e) {
//            System.err.println("MemcachedClient operation timeout");
//            e.printStackTrace();
//        } catch (InterruptedException e) {
//            // ignore
//        }
//    try {
//              //close memcached client
//                memcachedClient.shutdown();
//    } catch (IOException e) {
//                System.err.println("Shutdown MemcachedClient fail");
//                e.printStackTrace();
//    }
    }
    public void alitterTest()throws Exception{
    	MemcachedClient client=new XMemcachedClient("localhost",11211);

    	//同步存储value到memcached
    	client.set("key",3600,"Hello World");
    	//从memcached获取key对应的value
    	Object someObject=client.get("key");
    	
    	System.out.println(someObject);
    	//从memcached获取key对应的value,操作超时2秒
    	someObject=client.get("key",2000);

    	//删除value
    	client.delete("key");
    }
    public static void main(String[] args) throws Exception{
		new Cache().alitterTest();
	}
}
